import { useEffect, useState } from 'react'
import './App.css'
import type { PointData, SelectedPoint, TimeRange, SearchResult } from './types'
import { calculateDistance, calculateTimeSpan, mergeOverlappingPoints, createCustomIcon, createPopupContent } from './utils/mapUtils'
import SearchPanel from './components/SearchPanel'
import DistanceInfoPanel from './components/DistanceInfoPanel'
import MapContainer from './components/MapContainer'
import pointsDataJson from './data/points_data.json'

function App() {
  // 选中的点状态
  const [selectedPoints, setSelectedPoints] = useState<SelectedPoint[]>([])
  const [distanceInfo, setDistanceInfo] = useState<{
    distance: number;
    timeSpan: string;
    point1: string;
    point2: string;
  } | null>(null)
  
  // 时间轴相关状态
  const [selectedTimeRange, setSelectedTimeRange] = useState<TimeRange | null>(null)
  
  // 搜索相关状态
  const [focusPoint, setFocusPoint] = useState<{ latitude: number; longitude: number } | undefined>()
  
  // 从JSON文件导入点数据
  const [pointsData] = useState<PointData[]>(pointsDataJson as PointData[])

  // 初始化时间范围
  useEffect(() => {
    const times = pointsData.map(p => new Date(p.time))
    const minTime = new Date(Math.min(...times.map(t => t.getTime())))
    const maxTime = new Date(Math.max(...times.map(t => t.getTime())))
    
    setSelectedTimeRange({ start: minTime, end: maxTime })
  }, [pointsData])

  // 清除选择
  const clearSelection = () => {
    setSelectedPoints([])
    setDistanceInfo(null)
  }

  // 处理点选择
  const handlePointSelect = (selectedPoint: SelectedPoint) => {
    setSelectedPoints(prev => {
      // 检查是否已经选中
      const existingIndex = prev.findIndex(p => p.index === selectedPoint.index)
      if (existingIndex !== -1) {
        // 如果已选中，则取消选择
        const newSelected = prev.filter(p => p.index !== selectedPoint.index)
        return newSelected
      }
      
      if (prev.length >= 2) {
        // 如果已选中2个点，替换第一个点
        const [, ...rest] = prev
        return [...rest, selectedPoint]
      } else {
        // 添加到选中列表
        return [...prev, selectedPoint]
      }
    })
  }

  // 处理搜索结果选择
  const handleSearchResultSelect = (result: SearchResult) => {
    setFocusPoint({
      latitude: result.data.latitude,
      longitude: result.data.longitude
    })
  }

  // 处理选中点变化 - 计算距离
  useEffect(() => {
    if (selectedPoints.length === 2) {
      const [point1, point2] = selectedPoints
      
      // 根据时间确定起点和终点
      const time1 = new Date(point1.point.contents[0].time)
      const time2 = new Date(point2.point.contents[0].time)
      const isPoint1Earlier = time1.getTime() < time2.getTime()
      
      const startPoint = isPoint1Earlier ? point1 : point2
      const endPoint = isPoint1Earlier ? point2 : point1
      
      // 计算距离
      const distance = calculateDistance(
        startPoint.point.latitude, startPoint.point.longitude,
        endPoint.point.latitude, endPoint.point.longitude
      )
      
      // 计算时间跨度
      const timeSpan = calculateTimeSpan(
        startPoint.point.contents[0].time,
        endPoint.point.contents[0].time
      )
      
      // 设置距离信息
      setDistanceInfo({
        distance,
        timeSpan,
        point1: startPoint.point.contents[0].hoverContent,
        point2: endPoint.point.contents[0].hoverContent
      })
    } else {
      setDistanceInfo(null)
    }
  }, [selectedPoints])

  return (
    <div style={{ display: 'flex', width: '100%', height: '100vh' }}>
      {/* 搜索面板 */}
      <SearchPanel 
        pointsData={pointsData}
        onSearchResultSelect={handleSearchResultSelect}
      />
      
      {/* 地图和控制面板区域 */}
      <div style={{ flex: 1, position: 'relative', display: 'flex', flexDirection: 'column' }}>
        {/* 页面标题 */}
        <div style={{ 
          padding: '16px 20px', 
          borderBottom: '1px solid rgba(0, 0, 0, 0.1)',
          background: 'rgba(255, 255, 255, 0.95)',
          backdropFilter: 'blur(10px)',
          flexShrink: 0
        }}>
          <h1 style={{ textAlign: 'center', margin: '0 0 8px 0', fontSize: '20px' }}>半部电台地图</h1>
          <div style={{ textAlign: 'center', marginBottom: '4px', fontSize: '13px', color: '#666' }}>
            默认显示立体地形阴影图，可使用右上角图层控制器切换不同地形效果
          </div>
          <div style={{ textAlign: 'center', marginBottom: '4px', fontSize: '11px', color: '#888' }}>
            🏔️ 地形阴影 | 🛰️ 卫星图像 | 📍 等高线 | 🗺️ 混合地形 等多种立体地图可选
          </div>
          <div style={{ textAlign: 'center', marginBottom: '4px', fontSize: '11px', color: '#888' }}>
            共 {pointsData.length} 个数据点，合并后 {mergeOverlappingPoints(pointsData).length} 个标记点 | 📏 点击两个点查看时间轨迹 | 🔍 左侧可搜索地点和内容
          </div>
          <div style={{ textAlign: 'center', fontSize: '10px', color: '#aaa' }}>
            ⏰ 自动按时间顺序：蓝色(早期) → 紫色(中期) → 红色(晚期) | 🖱️ 悬浮连线显示距离详情
          </div>
        </div>

        {/* 距离信息面板 */}
        {distanceInfo && (
          <DistanceInfoPanel 
            distanceInfo={distanceInfo}
            onClearSelection={clearSelection}
          />
        )}

        {/* 地图容器 */}
        <MapContainer
          pointsData={pointsData}
          selectedTimeRange={selectedTimeRange}
          selectedPoints={selectedPoints}
          onPointSelect={handlePointSelect}
          focusPoint={focusPoint}
          mergeOverlappingPoints={mergeOverlappingPoints}
          createCustomIcon={(count, isSelected, mergedPoint) => 
            createCustomIcon(count, isSelected, mergedPoint, selectedTimeRange)
          }
          createPopupContent={(mergedPoint) => 
            createPopupContent(mergedPoint, selectedTimeRange)
          }
        />
      </div>
    </div>
  )
}

export default App 